package com.gravata.enigma.fragments;

import java.sql.SQLException;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.gravata.enigma.Confirm;
import com.gravata.enigma.R;
import com.gravata.enigma.RegrasApplyer;
import com.gravata.enigma.ReloadDataListener;
import com.gravata.enigma.activities.FiltroActivity;
import com.gravata.enigma.activities.RegraActivity;
import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.adapter.RegrasAdapter;
import com.gravata.enigma.model.Filtro;
import com.gravata.enigma.model.Regra;
import com.gravata.enigma.quickaction.QuickActionBar;
import com.gravata.enigma.quickaction.QuickActionIcons;

public class RegrasFragment extends Fragment implements ReloadDataListener {

	/** group items */
	private ExpandableListView eList;
	private RegrasAdapter regraAdapter;
	private QuickActionBar qab;
	private ReloadDataListener dataListener=this;


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_regras, container,
				false);
		Button btnAdd=(Button) rootView.findViewById(R.id.regra_add);

	    btnAdd.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent=new Intent(getActivity(),RegraActivity.class);
					startActivityForResult(intent, TelaInicial.REGRA_INSERT);
				}
			});

		eList = (ExpandableListView) rootView
				.findViewById(R.id.regras_list);
		eList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		regraAdapter = new RegrasAdapter(this.getActivity(),
				TelaInicial.regras);

		eList.setAdapter(regraAdapter);
		eList.setLongClickable(true);

		eList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
			int previousGroup = -1;

			@Override
			public void onGroupExpand(int groupPosition) {
				if (groupPosition != previousGroup)
					eList.collapseGroup(previousGroup);
				previousGroup = groupPosition;
			}
		});

		final QuickActionIcons add = new QuickActionIcons();

		add.setTitle(getString(R.string.adicionar));
		add.setIcon(getResources()
				.getDrawable(android.R.drawable.ic_menu_edit));
		add.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),FiltroActivity.class);
				int request = -1;

				if (qab.getChildPosition() == -1) {

					intent.putExtra("regra",regraAdapter.getGroup(qab.getGroupPosition()));
					request = TelaInicial.REGRA_INSERT;
					collapseAll();
				}
				qab.hide();

				startActivityForResult(intent, request);
			}

		});

		final QuickActionIcons edit = new QuickActionIcons();

		edit.setTitle(getString(R.string.editar));
		edit.setIcon(getResources()
				.getDrawable(android.R.drawable.ic_menu_edit));
		edit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (qab.getChildPosition() !=-1) {
					Filtro filtro=regraAdapter.getChild(qab.getGroupPosition(), qab.getChildPosition());

					editarFiltro(filtro);
				}else{
					Regra regra=regraAdapter.getGroup(qab.getGroupPosition());
					Intent intent=new Intent(getActivity(),RegraActivity.class);
					intent.putExtra("regra", regra);
					startActivityForResult(intent, TelaInicial.REGRA_EDIT);
					collapseAll();
				}
				qab.hide();
			}

		});

		final QuickActionIcons excluir = new QuickActionIcons();

		excluir.setTitle(getString(R.string.excluir));
		excluir.setIcon(getResources().getDrawable(
				android.R.drawable.ic_menu_delete));
		excluir.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Confirm confirm = new Confirm(getActivity(),
						getString(R.string.confirmar_exclusao),
						getString(R.string.confirmar_exclusao_regra),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								String name="";
								if(qab.getChildPosition()!=-1){
									Filtro filtro=regraAdapter.getChild(qab.getGroupPosition(), qab.getChildPosition());
									try {
										name=filtro.getFiltro();
										TelaInicial.repositorioFiltro.excluir(filtro);
										TelaInicial.reloadRegras();
										regraAdapter.setData(TelaInicial.regras);
									} catch (SQLException e) {
									}
								}else{
									Regra regra= regraAdapter.getGroup(qab.getGroupPosition());
									try {
										name=regra.getName();
										TelaInicial.repositorioRegra.excluir(regra);
										TelaInicial.reloadRegras();
										regraAdapter.setData(TelaInicial.regras);
									} catch (SQLException e) {
									}
								}

								qab.hide();

								Toast.makeText(getActivity(),name+ " "+getString(R.string.excluido_sucesso),Toast.LENGTH_SHORT).show();
								regraAdapter.notifyDataSetChanged();

							}
						}, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								qab.hide();
							}
						});
				confirm.show();
			}

		});

		 final QuickActionIcons aplicarRegras = new QuickActionIcons();

		 aplicarRegras.setTitle(getString(R.string.aplicar_regras));
		 aplicarRegras.setIcon(getResources().getDrawable(android.R.drawable.ic_menu_set_as));
		 aplicarRegras.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					final Regra regra=regraAdapter.getGroup(qab.getGroupPosition());

					qab.hide();
					Confirm confirm = new Confirm(getActivity(),
							getString(R.string.aplicar_regras),
							getString(R.string.manter_canais),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new RegrasApplyer(getActivity(),false,dataListener).execute(regra);
									//regraAdapter.notifyDataSetChanged();

								}
							}, new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new RegrasApplyer(getActivity(),true,dataListener).execute(regra);
									//regraAdapter.notifyDataSetChanged();
								}
							});
					confirm.show();
				}

			});

		eList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {


				int itemtype = ExpandableListView.getPackedPositionType(id);
				int childPosition=-1;
				int groupPosition;
				if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
					childPosition =ExpandableListView.getPackedPositionChild(id);
					groupPosition=ExpandableListView.getPackedPositionGroup(id);
				}else{
					groupPosition=ExpandableListView.getPackedPositionGroup(id);
				}


				qab = new QuickActionBar(view);

				qab.setChildPosition(childPosition);
				qab.setGroupPosition(groupPosition);

				if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_GROUP){
					qab.addItem(add);
				}

				if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
					qab.addItem(edit);
					qab.addItem(excluir);
				}else{

					Regra regra=regraAdapter.getGroup(groupPosition);
					if(!regra.isFavorito() && !regra.isExclude()){
						qab.addItem(edit);
						qab.addItem(excluir);
					}
				}

				if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_GROUP){
					qab.addItem(aplicarRegras);
				}
				qab.setAnimationStyle(QuickActionBar.GROW_FROM_LEFT);
				qab.show();

				return true;
			}
		});

		eList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView arg0, View view, int groupPosition, int childPosition, long id) {

				Filtro filtro=regraAdapter.getChild(groupPosition, childPosition);

				editarFiltro(filtro);

				return false;
			}
		});

		return rootView;
	}

	private void editarFiltro(Filtro filtro){
		Intent intent = new Intent(getActivity(),
				FiltroActivity.class);
		int request = TelaInicial.REGRA_EDIT;
		intent.putExtra("filtro",filtro);

		collapseAll();
		startActivityForResult(intent, request);
	}

	private void collapseAll() {
		int count = regraAdapter.getGroupCount();

		for (int a = 0; a < count; a++)
			eList.collapseGroup(a);
	}

	@Override
	public void onResume() {
		super.onResume();
		regraAdapter.setData(TelaInicial.regras);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode >0) {
			TelaInicial.reloadRegras();
			regraAdapter.notifyDataSetChanged();
			eList.invalidateViews();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onReloadData() {
		if(regraAdapter!=null)
			regraAdapter.notifyDataSetChanged();
	}

	@Override
	public void onFealoadData(List<?> list) {
		// TODO Auto-generated method stub

	};

}
